package com.shitou.shitoucommons.utils;


import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.UUID;

/**
 * class detail:
 *
 * @author 石头人
 */
@SuppressWarnings("all")
public class TokenGenerator {

    private static final char[] hexCode = "sh3ito2344u7resd4fnd6ealksjd5asfmull".toCharArray();

    public static String generatorValue(){
        return generatorValue(UUID.randomUUID().toString());
    }

    public static String generatorValue(String param){
        try {
            // 用MD5算法生成
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            md5.update(param.getBytes(StandardCharsets.UTF_8));
            byte[] messageDigest = md5.digest();
            return toHexString(messageDigest);
        } catch ( Exception e){
            throw new RuntimeException("生成token异常");
        }
    }

    /**
     * 将bytes数组转换为 string
     * @param bytes
     * @return
     */
    public static String toHexString(byte[] bytes){
        if ( bytes == null ) {
            return null;
        }

        StringBuilder stringBuilder = new StringBuilder(bytes.length*4);
        for (byte aByte : bytes) {
            // 进行 位移运算和与运算
            stringBuilder.append(hexCode[(aByte >> 4) & 0xF]);
            stringBuilder.append(hexCode[aByte & 0XF]);
        }

        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        System.out.println(generatorValue());
    }

}
